package com.atgion.manager.service.impl.client;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import com.atgion.manager.mapper.ArticleMapper;
import com.atgion.manager.service.client.ArchiveService;
import com.atgion.spzx.model.bo.blog.ArticleDO;
import com.atgion.spzx.model.vo.base.PageResponse;
import com.atgion.spzx.model.vo.base.Result;
import com.atgion.spzx.model.vo.blog.client.QueryArchiveItemRspVO;
import com.atgion.spzx.model.vo.blog.client.QueryArchivePageListReqVO;
import com.atgion.spzx.model.vo.blog.client.QueryArchivePageListRspVO;
import com.atgion.spzx.model.vo.blog.client.QueryIndexArticlePageItemRspVO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.YearMonth;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;

/**
 * @author: 犬小哈
 * @url: www.quanxiaoha.com
 * @date: 2023-04-17 12:08
 * @description: TODO
 **/
@Service
@Slf4j
public class ArchiveServiceImpl extends ServiceImpl<ArticleMapper, ArticleDO> implements ArchiveService {

    @Autowired
    private ArticleMapper articleMapper;

    @Override
    public Result<PageResponse<QueryArchivePageListRspVO>> queryArchive(QueryArchivePageListReqVO queryArchivePageListReqVO) {
        Long current = queryArchivePageListReqVO.getCurrent();
        Long size = queryArchivePageListReqVO.getSize();

        Page<ArticleDO> page = new Page<>(current, size);
        QueryWrapper<ArticleDO> wrapper = new QueryWrapper<>();
        wrapper.lambda().orderByDesc(ArticleDO::getCreateTime);
        IPage<ArticleDO> articleDOIPage = articleMapper.selectPage(page, wrapper);
        List<ArticleDO> records = articleDOIPage.getRecords();

        List<QueryArchivePageListRspVO> list = Lists.newArrayList();
        List<QueryArchiveItemRspVO> itemRspVOList = null;
        if (!CollectionUtils.isEmpty(records)) {

            itemRspVOList = records.stream()
                    .map(articleDO -> QueryArchiveItemRspVO.builder()
                            .id(articleDO.getId())
                            .titleImage(articleDO.getTitleImage())
                            .title(articleDO.getTitle())
                            .createMonth(articleDO.getCreateTime() != null ? 
                                DateUtil.format(articleDO.getCreateTime(), DatePattern.NORM_MONTH_PATTERN) : "")
                            .createTime(articleDO.getCreateTime() != null ? DateUtil.format(articleDO.getCreateTime(), DatePattern.NORM_MONTH_PATTERN):"")
                            .build())
                    .collect(Collectors.toList());


            Map<String, List<QueryArchiveItemRspVO>> map = itemRspVOList.stream().collect(Collectors.groupingBy(QueryArchiveItemRspVO::getCreateMonth));
            Map<String, List<QueryArchiveItemRspVO>> sortedMap = new TreeMap<>(new MonthKeyComparator());
            sortedMap.putAll(map);

            sortedMap.forEach((k, v) -> list.add(QueryArchivePageListRspVO.builder().month(k).articles(v).build()));
        }
        return Result.success(PageResponse.success(articleDOIPage, list));
    }

    class MonthKeyComparator implements Comparator<String> {
        @Override
        public int compare(String o1, String o2) {
            // 对空字符串或 null 值进行处理
            if (o1 == null || o1.isEmpty()) {
                return o2 == null || o2.isEmpty() ? 0 : 1;
            }
            if (o2 == null || o2.isEmpty()) {
                return -1;
            }
            
            // 使用 YearMonth 类将字符串解析成日期，并根据日期进行倒序排序
            YearMonth ym1 = YearMonth.parse(o1);
            YearMonth ym2 = YearMonth.parse(o2);
            return ym2.compareTo(ym1);
        }
    }
}
